/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.dishes;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.*;
import com.qinyeit.serviceapp.service.dishes.*;
import com.qinyeit.serviceapp.service.thirdpart.BranchPlatformApiServiceImpl;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * ClassName: DishessController <br/>
 * Function: dishes [套餐] <br/>
 * date: 2018-11-23 11:45:37 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/dishes/dishesPackages")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_dishes:read",name ="套餐",deleteAble = false)
public class DishesPackagesController extends BaseManagementController{

	@Autowired
	private DishesService dishesService;
	@Autowired
    private DishesSpecificationRelationService dishesSpecificationRelationService;
	@Autowired
    private DishesMakeRelationService dishesMakeRelationService;
	@Autowired
    private DishesFeedRelationService dishesFeedRelationService;
	@Autowired
    private DishesCategoryService dishesCategoryService;
	@Autowired
    private DishesPackageGroupService dishesPackageGroupService;
	@Autowired
    private BranchPlatformApiServiceImpl branchPlatformApiService;
	@Autowired
    private DishesPackageDetailService dishesPackageDetailService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","storeId","name","spell","pinyin","no","nameEn","category","unitId","weigh","season",
            "printCategoryId","commission","commissionType","commissionValue","futureCost","price","vipPrice","hot","recommend",
            "img","introduction","state","rank","type","packType","priceMode","createAt","count"};

    @RequiresPermissions("management_dishes:show")
    @PermissionInfo(code = "management_dishesPackages:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable,Long storeId){
        if(storeId==null){
            return fail("查询失败");
        }
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        searchable.addSearchParam("storeId_eq",storeId);
        searchable.addSearchParam("type_eq",DishesType.PACKAGE);
        Page<Dishes> dishesPage = dishesService.findAll(searchable);
        if(CollectionUtils.isNotEmpty(dishesPage.getContent())){
            for (Dishes dishes : dishesPage.getContent()) {
                searchable = SearchableUtils.newSearchableWithMerchantFilter();
                searchable.addSearchParam("packId_eq",dishes.getId());
                long count = dishesPackageDetailService.count(searchable);
                log.info("count >>>>>>>>>>: ",count);
                dishes.setCount(count);
            }
        }
        QyMap map  = QyMap.map("packageTypes",PackageType.values())
                .setv("dishesPage",JSONUtils.include(dishesPage,new Class[]{DishesState.class,PackageType.class}, keys));
        return ok("查询成功", map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Long storeId){
        if(storeId==null){
            return fail("查询失败");
        }
        QyMap map=QyMap.NEW();
        Dishes dishes = new Dishes();
        dishes.setNo(dishesService.getNextNo(DishesType.PACKAGE, "01",CurrentAccountUtils.getAuthenticatedMerchantGroupID()));
        map.setv("dishes",JSONUtils.include(dishes, keys));
        initFormDate(map,storeId);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesPackages:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject data, BindingResult bindingResult){
//        if(dishesService.exists(buildExists(null, "no", dishes.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        dishesService.savePackageData(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute Dishes dishes){
        return ok("查询成功", JSONUtils.include(dishes, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute Dishes dishes,Long storeId){
        if (storeId==null){
            return fail("查询失败",10001);
        }
        QyMap map=QyMap.NEW();
        map.setv("dishes",JSONUtils.include(dishes, keys));
        Searchable searchable=SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSort(Sort.Direction.ASC,"id");
        searchable.addSearchParam("packId_eq",dishes.getId());
        List<DishesPackageGroup> dishesPackageGroupList=dishesPackageGroupService.findWithSort(searchable);
        List<Map<String ,Object>> mapList = Lists.newArrayList();
        Map<String,Object> group=null;
        List<Map<String,Object>> packDetails=dishesService.getPackDetails(dishes);
        List<Map<String,Object>> groupDetails=null;
        for(DishesPackageGroup item:dishesPackageGroupList){
            group = Maps.newHashMap();
            group.put("name",item.getName());
            group.put("count",item.getCount());
            group.put("hasRepeat",item.getHasRepeat());
            group.put("id",item.getId());
            group.put("total",item.getTotal());
            groupDetails=Lists.newArrayList();
            for(Map<String,Object> itemDetail:packDetails){
                if(Long.valueOf(itemDetail.get("disheGroupId").toString()).equals(item.getId())){
                    if(dishes.getPackType()==PackageType.EASYPACKAGE){
                        if(Boolean.valueOf(itemDetail.get("isAlternative").toString())){
                            groupDetails.add(0, itemDetail);
                            continue;
                        }
                    }
                    groupDetails.add(itemDetail);
                }
            }
            Collections.reverse(groupDetails);
            group.put("selectDishes",groupDetails);
            mapList.add(group);
        }
        map.setv("dishesPackage",mapList);

        initFormDate(map,storeId);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesPackages:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject data,BindingResult bindingResult){
//        if(dishesService.exists(buildExists(null, "no", dishes.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        dishesService.savePackageData(data, CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesPackages:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        Dishes dishes = dishesService.findById(id);
        boolean boo = branchPlatformApiService.deleteBranchDishesData(dishes.getUuid());
        if (!boo){
            return fail("已使用，不能删除");
        }
        dishes.setUpdateTimestamp(DateUtils.current());
        dishesService.update(dishes);
        //删除套餐明细
        dishesService.deletedPackageDetails(id);
        dishesService.logicDelete(id);
        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            Dishes dishes = dishesService.findById(Long.valueOf(id));
            model.addAttribute(dishes);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap,Long storeId){
        //套餐类型
        qyMap.setv("packageType",PackageType.values());
        //定价模式
        qyMap.setv("priceMode",PriceMode.values());

        //在售/停售
        qyMap.setv("dishesStates", DishesState.values());
        //菜品类别
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("storeId_eq",storeId);
        searchable.addSearchParam("no_ne","00000");
        List<DishesCategory> categoryList = dishesCategoryService.findWithSort(searchable);
        qyMap.setv("categoryList",JSONUtils.include(categoryList,"id","no","name","state"));
        //菜品
        Page<Map<String,Object>> mapPage = dishesService.getDishesData(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),
                storeId,null,"",Searchable.newSearchable().setPage(0,15));
        qyMap.setv("dishess",mapPage);

    }

}